import { commonApi } from './api/common'
import { userApi } from './api/user'
import { getDomoUser, getNotifications, getUser } from './store/actions'
import { getServer, isLogin, setCurrencyName, setServer } from './store/mutations'
import { GlobalData } from './store/state'
import { $event, $logger } from './utils'
/** 客服 */
// import { plugin } from './utils/Openaiwidget'
/**环信 */
// import sdk = require('/utils/WebIM')

// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
// eslint-disable-next-line no-undef
// const WebIM = (wx.WebIM = sdk.default)
// import msgStorage = require('/comps/chat/msgstorage')
// import msgType = require('/comps/chat/msgtype')
function ack(receiveMsg: any) {
  // 处理未读消息回执
  // const bodyId = receiveMsg.id // 需要发送已读回执的消息id
  // const ackMsg = new WebIM.message('read', WebIM.conn.getUniqueId())
  // ackMsg.set({
  //   id: bodyId,
  //   to: receiveMsg.from,
  // })
  // WebIM.conn.send(ackMsg.body)
}
// function onMessageError(err: any) {
//   return err.type !== 'error'
// }
function calcUnReadSpot(message = '') {
  const myName = GlobalData.imVersion + getUser().id
  wx.getStorageInfo({
    success: function (res) {
      const storageKeys = res.keys
      const newChatMsgKeys = [] as any
      const len = myName.length
      // const historyChatMsgKeys = []
      storageKeys.forEach((item) => {
        if (item.slice(-len) == myName && item.indexOf('rendered_') == -1) {
          newChatMsgKeys.push(item)
        }
      })
      const count = newChatMsgKeys.reduce(function (result: any, curMember: string) {
        const chatMsgs = wx.getStorageSync(curMember) || []
        return result + chatMsgs.length
      }, 0)

      GlobalData.unReadMessageNum = count
      getNotifications()
      $event.emit('em.xmpp.unreadspot', message)
      $event.emit('new-sum')
    },
  })
}

App({
  data: {
    timer: '' as any,
  },
  conn: {
    closed: false,
    curOpenOpt: {},
    open(opt: any) {
      // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
      // @ts-ignore
      // // this.curOpenOpt = opt
      // // WebIM.conn.open(opt)
      // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
      // @ts-ignore
      // this.closed = false
    },
    reopen() {
      // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
      // @ts-ignore
      if (this.closed) {
        //this.open(this.curOpenOpt);
        // // WebIM.conn.open(this.conn.curOpenOpt)
        // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
        // @ts-ignore
        // // this.closed = false
      }
    },
  },
  onShow(options) {
    $logger.debug('App onShow', { options })
  },
  onHide() {},
  async onLaunch() {
    await this.initDeviceInfo()
    // 调用 API 从本地缓存中获取数据
    wx.setInnerAudioOption({ obeyMuteSwitch: false })
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    $event.on('em.main.ready', { is: 'App' }, () => {
      calcUnReadSpot()
    })
    $event.on('em.chatroom.leave', { is: 'App' }, () => {
      calcUnReadSpot()
    })
    $event.on('em.chat.session.remove', { is: 'App' }, () => {
      calcUnReadSpot()
    })
    $event.on('em.chat.audio.fileLoaded', { is: 'App' }, () => {
      calcUnReadSpot()
    })

    $event.on('em.main.deleteFriend', { is: 'App' }, () => {
      calcUnReadSpot()
    })
    $event.on('em.chat.audio.fileLoaded', { is: 'App' }, () => {
      calcUnReadSpot()
    })
    this.checkPackage()
    setServer('prod' as DomoServer)
    $event.on('boot', { is: 'App' }, async () => {
      this.initBootstrappers()
    })
    $event.on('after:login', { is: 'App' }, async () => {
      /** 会员配置 */
      if (!GlobalData!.vip) {
        GlobalData.vip = await this.getVipInfo()
      }
      const loginReward = await userApi.getLoginReward()
      if (loginReward.amount) {
        $event.emit('showMessage', {
          message: '每日登录',
          amount: loginReward.amount,
        } as GetRewardMessageReturns)
      }
      if (GlobalData!.userAbilities.length === 0) {
        // GlobalData.userAbilities = await userApi.abilitiesList()
        // $event.emit('after:abilities')
      }
      // const user = wx.getStorageSync(`${getServer()}/logged`).data
      // this.initCustomerService(user)
      /** 请求消息列表 */
      getNotifications()
      /** 初始化聊天 */
      if (GlobalData.hasIM && !GlobalData.imLogged) {
        // GlobalData.imLogged = true
        // this.imModule()
      }
      $event.off('after:login', { is: 'App' })
    })
    $event.on('after:registerInfo', { is: 'App' }, async () => {
      $event.emit('showMessage', {
        message: '首次登陆',
        amount: GlobalData.register_score,
      } as GetRewardMessageReturns)
      // const user = wx.getStorageSync(`${getServer()}/logged`).data
      // const code = wx.getStorageSync('invite') || 0
      /** 初始化客服 */
      // this.initCustomerService(user)
      /** 之前可能会涉及到设置错误的邀请码,所以这里判断了''和undefined */
      // !user.inviter && code && code != '' && code != user.invite_code
      //   ? userApi.setInvitee({ invite_code: code })
      //   : ''
      // wx.navigateTo({
      //   url: '/mine/setting/setting',
      // })
    })
    wx.nextTick(() => {
      this.initBootstrappers()
    })
    /** 设置定时器获取设备信息 */
    if (!GlobalData.navigationHeight && !GlobalData.bootTime) {
      GlobalData.bootTime = setInterval(() => {
        this.initDeviceInfo()
        if (GlobalData.navigationHeight) {
          clearInterval(GlobalData.bootTime)
        }
      }, 60000)
    }
  },

  /**
   * 初始化客服
   */
  initCustomerService(user: any) {
    const openAiAppId = '{{OPENAI_APPID}}'
    if (openAiAppId) {
      /** 客服初始化 */
      // plugin.init({
      //   appid: openAiAppId, //小程序示例账户，仅供学习和参考
      //   openid: wx.getStorageSync(`${getServer()}/openId`).data, //用户的openid，必填项，可通过wx.login()获取code，然后通过后台接口获取openid
      //   userHeader: user.avatar?.url, // 用户头像
      //   userName: user.name, // 用户昵称
      //   guideList: ['常见问题'],
      //   anonymous: false, // 是否允许匿名用户评价，默认为false，设为ture时，未传递userName、userHeader两个字段时将弹出登录框
      //   success: () => {
      //     console.log('------customservice success--------')
      //   }, //非必填
      //   fail: (error: any) => {
      //     console.log(error)
      //   }, //非必填
      // })
    }
  },
  /**
   * 检测更新
   */
  async checkPackage() {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                }
              },
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
            })
          })
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
      })
    }
  },
  /**
   * 初始化设备信息
   *
   * 用于获取导航栏布局、滑动切换页面所需的信息
   */
  async initDeviceInfo() {
    const res = wx.getSystemInfoSync()
    GlobalData.clientHeihgt = res.windowHeight
    GlobalData.clientWidth = res.windowWidth
    GlobalData.system = res.platform

    if (res.screenHeight - res.safeArea.height > 40) {
      GlobalData.isFullScreen = true
    }

    if (res.model.search('iPhone X') !== -1) {
      GlobalData.isIPX = true
    }
    /** 电脑小程序劝退 */
    if (res.platform != 'ios' && res.platform != 'android' && res.platform != 'devtools') {
      // wx.showModal({
      //   title: '提示',
      //   content: '电脑端的体验尚不完善，请您在手机上进行所有的发布操作',
      // })
    }

    const rect = await wx.getMenuButtonBoundingClientRect()
    GlobalData.menuRect = rect
    GlobalData.navigationHeight = rect.top + rect.height + 10
  },

  /** 获取启动信息 */
  async initBootstrappers() {
    try {
      const {
        mall = {},
        currency = {},
        invite = {},
        knowledge = {},
        register_score = 0,
        wallet = {},
        wechat_mini_program: config = {},
        site: { currency_name: { name = '积分' } = {}, reward: { status = false } = {} } = {},
        ['im:helper-user']: imHelpUser = 0,
        ['im:open']: imOpen = true,
        ['im:prefix']: imPrefix = '',
        ['file-storage']: fileStorage,
      } = await commonApi.getBootstrppers()
      if (fileStorage) {
        const { ['default-filesystem']: defaultFilesystem } = fileStorage
        GlobalData.fileStorage.fileSystem = defaultFilesystem
        GlobalData.fileStorage.acl = fileStorage?.acl
      }
      GlobalData.imVersion = imPrefix
      GlobalData.imHelper = imHelpUser
      GlobalData.hasIM = imOpen
      GlobalData.mall = mall
      GlobalData.wallet = wallet
      GlobalData.knowledge = knowledge
      GlobalData.currency = currency
      GlobalData.access.ugc = config.ugc || false
      GlobalData.access.video = config.video || false
      GlobalData.access.reward = config.reward && status
      // GlobalData.access.download = config.download || false  下载功能已不再支持
      GlobalData.access.download = false
      GlobalData.access.secCheck = config.secCheck || false
      // 积分名字
      setCurrencyName(name)
      GlobalData.currencyName = name
      GlobalData.invite = invite
      GlobalData.register_score = register_score
      GlobalData.rewardGiftList = await commonApi.getRewardGiftList()
      /** 广告 */
      const ids = [] as any
      GlobalData.advertisingspace = await commonApi.getAdvertisingspace()
      GlobalData.advertisingspace.forEach((item: { id: string }) => {
        ids.push(item.id)
      })
      // eslint-disable-next-line require-atomic-updates
      GlobalData.advertisingList = await commonApi.getAdvertisingList({ space: ids.toString() })
      /** 话题配置 */
      // eslint-disable-next-line require-atomic-updates
      GlobalData.themeConfig = await commonApi.getThemeConfig()
      /** 用户权限 */
      $event.emit('after:rewardGiftList')
      $event.emit('after:boot')
      /** 初始化聊天 */
      if (GlobalData.hasIM) {
        this.imModule()
      }
      if (isLogin()) {
        getNotifications()
        // GlobalData.userAbilities = await userApi.abilitiesList()
        $event.emit('after:abilities')
        await getDomoUser()
        const user = wx.getStorageSync(`${getServer()}/logged`).data
        /** 初始化客服 */
        this.initCustomerService(user)
      }
    } catch (error) {
      console.log(error)
      wx.showToast({
        title: '加载失败',
        icon: 'none',
        duration: 1000,
      })
      wx.hideLoading()
    }
  },
  /** 会员卡配置信息 */
  async getVipInfo(): Promise<DomoVip> {
    const vipData = await userApi.getVipConfig()
    /** 处理VIP数据,取成自己想要的格式 */
    const vip = {} as DomoVip
    vip.switch = vipData.switch
    vip.exchange = vipData.exchange ? vipData.exchange : ''
    vip.config = []
    vipData.config.low && vipData.config.low.enable ? vip.config.push(vipData.config.low) : ''
    vipData.config.middle && vipData.config.middle.enable
      ? vip.config.push(vipData.config.middle)
      : ''
    vipData.config.high && vipData.config.high.enable ? vip.config.push(vipData.config.high) : ''
    vip.config = vip.config.filter((item: DomoVipItem) => {
      return (item.setting = item.setting.filter((items) => {
        return items.enable
      }))
    })
    return vip
  },
  /** 环信IM */
  async imModule() {},
})
